#include"hash_table.h"
using namespace std;

template<class K,class E>
hashTable<K, E>::hashTable(int theDivisor)
{
	divisor = theDivisor;
	dSize = 0;
	table = new pair<const K, E>* [divisor];
	for (int i = 0; i < divisor; ++i)
		table[i] = NULL;
}

template<class K,class E>
int hashTable<K, E>::search(const K& theKey)const
{
	int i = (int)hash(theKey) % divisor;
	if (i < 0)
		i += divisor;
	int j = i;
	int count = 0;
	int maxCount = divisor;
	do
	{
		if (table[i] == NULL || table[i]->first == theKey)
			return j;
		j = (j + 1) % divisor;
		count++;
	} while (j != i && count < maxCount);

	return j;
}

template<class K,class E>
std::pair<const K, E>* hashTable<K, E>::find(const K& theKey)const
{
	int b = search(theKey);
	if (table[b] == NULL || table[b]->first != theKey)
		return NULL;
	return table[b];
}

template<class K,class E>
void hashTable<K, E>::insert(const std::pair<const K, E>&thePair)
{
	int b = search(thePair.first);
	if (table[b] == NULL)
	{
		table[b] = new pair<const K, E>(thePair);
		dSize++;
	}
	else
	{
		if (table[b]->first == thePair.first)
			table[b]->second = thePair.second;
		else
			cout << "Insert error!" << endl;
	}
}